<template>
  <div class="search-container">
    <form action="/">
      <van-sticky>
        <van-search
          v-model.trim="searchText"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="$router.back()"
          @focus="isShowResults = false"
          background="#3296fa"
        />
      </van-sticky>
    </form>
    <!-- 搜索结果 -->
    <SearchResults v-if="isShowResults" :searchText="searchText" />
    <!-- 搜索历史 -->
    <SearchHistory @search="onSearch" @deleteAll="deleteAll" :history="history" v-else-if="!searchText" />
    <!-- 搜索建议 -->
    <SearchSuggestion @clickitem='onSearch' :searchText="searchText" v-else />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResults from './components/search-results.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  data () {
    return {
      searchText: '',
      isShowResults: false,
      history: getItem('HMTT-HISTORY') || []
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  },
  created () {

  },
  watch: {
    history: {
      deep: true,
      handler () {
        setItem('HMTT-HISTORY', this.history)
      }
    }
  },
  methods: {
    onSearch (val) {
      if (val === '') return
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
      this.searchText = val
      this.isShowResults = true
    },
    deleteAll () {
      this.history = []
    }
  }
}
</script>

<style lang="less" scoped>
.search-container{
  .van-search__action{
    color: #fff;
  }
}
</style>
